// src/stores/sys/SysMenuStore.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'
import request from '@/utils/request'
import type { SysMenu, SysMenuCreation, SysMenuUpdate, SysMenuTree } from '@/types/sys/SysMenu'

// 模拟菜单数据 - 平面结构，通过parent_id关联，将被转换为树形结构
const mockMenus: SysMenu[] = [
  // 第一层菜单 - 工作台
  {
    menu_id: 1,
    menu_name: '任务工作台',
    menu_code: 'task',
    parent_id: 0,
    menu_level: 1,
    menu_path: '/home',
    component: 'home',
    icon: 'HomeFilled',
    sort_order: 0,
    is_active: true,
    description: '工作台模块',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 2,
    menu_name: '首页',
    menu_code: 'home_dashboard',
    parent_id: 1,
    menu_level: 2,
    menu_path: 'dashboard',
    component: 'dashboard',
    icon: 'Document',
    sort_order: 1,
    is_active: true,
    description: '首页',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 3,
    menu_name: '待办理任务',
    menu_code: 'pending',
    parent_id: 1,
    menu_level: 2,
    menu_path: 'pending',
    component: 'PendingTasks',
    icon: 'Document',
    sort_order: 2,
    is_active: true,
    description: '待办理任务',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 4,
    menu_name: '已办理任务',
    menu_code: 'completed',
    parent_id: 1,
    menu_level: 2,
    menu_path: 'completed',
    component: 'CompletedTasks',
    icon: 'Document',
    sort_order: 3,
    is_active: true,
    description: '已办理任务',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 5,
    menu_name: '我的任务',
    menu_code: 'mytasks',
    parent_id: 1,
    menu_level: 2,
    menu_path: 'mytasks',
    component: 'MyTasks',
    icon: 'Document',
    sort_order: 4,
    is_active: true,
    description: '我的任务',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 6,
    menu_name: '基础资料',
    menu_code: 'base',
    parent_id: 0,
    menu_level: 1,
    menu_path: 'base',
    component: 'Base',
    icon: 'Document',
    sort_order: 0,
    is_active: true,
    description: '基础资料',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 7,
    menu_name: '基础信息',
    menu_code: 'base',
    parent_id: 6,
    menu_level: 2,
    menu_path: 'base',
    component: 'base',
    icon: 'Document',
    sort_order: 1,
    is_active: true,
    description: '基础信息',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 8,
    menu_name: '车间资料',
    menu_code: 'workshop',
    parent_id: 7,
    menu_level: 2,
    menu_path: 'workshop',
    component: 'workshop',
    icon: 'Document',
    sort_order: 1,
    is_active: true,
    description: '车间资料',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 9,
    menu_name: '仓库资料',
    menu_code: 'warehouse',
    parent_id: 7,
    menu_level: 3,
    menu_path: 'warehouse',
    component: 'warehouse',
    icon: 'Document',
    sort_order: 3,
    is_active: true,
    description: '仓库资料',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 10,
    menu_name: '供应商资料',
    menu_code: 'supplier',
    parent_id: 7,
    menu_level: 3,
    menu_path: 'supplier',
    component: 'supplier',
    icon: 'Document',
    sort_order: 4,
    is_active: true,
    description: '供应商资料',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 11,
    menu_name: '客户资料',
    menu_code: 'customer',
    parent_id: 7,
    menu_level: 3,
    menu_path: 'customer',
    component: 'customer',
    icon: 'Document',
    sort_order: 5,
    is_active: true,
    description: '客户资料',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 12,
    menu_name: '货品信息',
    menu_code: 'product',
    parent_id: 6,
    menu_level: 2,
    menu_path: 'product',
    component: 'product',
    icon: 'Document',
    sort_order: 6,
    is_active: true,
    description: '货品信息',
    created_at: '2025-11-03T08:00:00Z',
    updated_at: '2025-11-03T14:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    menu_id: 13,
    menu_name: '系统管理',
    menu_code: 'SYS_MANAGE',
    parent_id: 0,
    menu_level: 1,
    menu_path: 'system',
    component: 'Layout',
    icon: 'Setting',
    sort_order: 9,
    is_active: true,
    description: '系统管理模块',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  // 第二层菜单 - 系统管理的子节点
  {
    menu_id: 14,
    menu_name: '用户与权限',
    menu_code: 'iam-user',
    parent_id: 13,
    menu_level: 2,
    menu_path: 'iam-user',
    component: 'UserManage',
    icon: 'Avatar',
    sort_order: 1,
    is_active: true,
    description: '用户与权限',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 15,
    menu_name: '用户管理',
    menu_code: 'iam-user',
    parent_id: 14,
    menu_level: 3,
    menu_path: 'iam-user',
    component: 'UserManage',
    icon: 'Avatar',
    sort_order: 1,
    is_active: true,
    description: '用户列表',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 16,
    menu_name: '角色列表',
    menu_code: 'iam-role',
    parent_id: 14,
    menu_level: 3,
    menu_path: 'iam-role',
    component: 'RoleManage',
    icon: 'Tickets',
    sort_order: 2,
    is_active: true,
    description: '角色列表',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 17,
    menu_name: '用户角色',
    menu_code: 'iam-user-role',
    parent_id: 14,
    menu_level: 3,
    menu_path: 'iam-user-role',
    component: 'system/UserRoleManage',
    icon: 'User',
    sort_order: 3,
    is_active: true,
    description: '用户角色',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 18,
    menu_name: '模块列表',
    menu_code: 'iam-module',
    parent_id: 14,
    menu_level: 3,
    menu_path: 'iam-module',
    component: 'MenuManage',
    icon: 'Menu',
    sort_order: 4,
    is_active: true,
    description: '模块列表',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 19,
    menu_name: '权限列表',
    menu_code: 'iam-permission',
    parent_id: 14,
    menu_level: 3,
    menu_path: 'iam-permission',
    component: 'iamPermissionPage',
    icon: 'Lock',
    sort_order: 4,
    is_active: true,
    description: '权限列表',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 20,
    menu_name: '角色授权',
    menu_code: 'iam-role-auth',
    parent_id: 14,
    menu_level: 3,
    menu_path: 'iam-role-auth',
    component: 'iamRoleAuthPage',
    icon: 'Check',
    sort_order: 4,
    is_active: true,
    description: '角色授权',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 21,
    menu_name: '页面与参数',
    menu_code: 'sys-menu-params',
    parent_id: 13,
    menu_level: 2,
    menu_path: 'iam-menu-params',
    component: 'MenuParamsManage',
    icon: 'Menu',
    sort_order: 1,
    is_active: true,
    description: '页面与参数',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 22,
    menu_name: '参数设定',
    menu_code: 'sys-params',
    parent_id: 21,
    menu_level: 3,
    menu_path: 'sys-params',
    component: 'SysParamsPage',
    icon: 'Document',
    sort_order: 1,
    is_active: true,
    description: '参数设定',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 23,
    menu_name: '页面菜单',
    menu_code: 'sys-menu',
    parent_id: 21,
    menu_level: 3,
    menu_path: 'sys-menu',
    component: 'sysMenuPage',
    icon: 'Menu',
    sort_order: 1,
    is_active: true,
    description: '页面菜单',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    menu_id: 24,
    menu_name: '操作日志',
    menu_code: 'sys-operation-log',
    parent_id: 21,
    menu_level: 3,
    menu_path: 'sys-operation-log',
    component: 'sysOperationLogPage',
    icon: 'Search',
    sort_order: 1,
    is_active: true,
    description: '操作日志',
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },

]

export const useSysMenuStore = defineStore('sysMenu', () => {
  // 菜单列表
  const menuList = ref<SysMenu[]>(mockMenus)
  const menuTree = ref<SysMenuTree[]>([])
  const currentMenu = ref<SysMenu | null>(null)
  const isEditing = ref(false)

  // 获取菜单列表
  const fetchMenuList = async (signal?: AbortSignal) => {
    try {
      const response = await request.get('/api/sys/menus', { signal })
      if (response && response.data) {
        menuList.value = response.data
        buildMenuTree()
      }
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('获取菜单列表失败:', error)
        // 使用模拟数据
        menuList.value = mockMenus
        buildMenuTree()
      }
    }
  }

  // 构建菜单树结构 - 支持多层级children
  const buildMenuTree = () => {
    const menus = [...menuList.value]
    const tree: SysMenuTree[] = []
    const map: Record<number, SysMenuTree> = {} as Record<number, SysMenuTree>

    // 初始化映射，将SysMenu转换为SysMenuTree
    menus.forEach(menu => {
      map[menu.menu_id] = { ...menu, children: [] }
    })

    // 构建树结构
    menus.forEach(menu => {
      // 确保 parent_id 存在且不为 undefined
      if (menu.parent_id === 0 || menu.parent_id === undefined) {
        tree.push(map[menu.menu_id])
      } else {
        // 确保 parent_id 存在后再访问 map
        const parentId = menu.parent_id
        const parent = map[parentId]
        if (parent) {
          parent.children = parent.children || []
          parent.children.push(map[menu.menu_id])
        }
      }
    })

    menuTree.value = tree
  }

  // 新增菜单
  const addMenu = async (menu: SysMenuCreation, signal?: AbortSignal) => {
    try {
      const response = await request.post('/api/sys/menus', menu, { signal })

      if (response && response.data) {
        menuList.value.push(response.data)
        buildMenuTree()
      }
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('新增菜单失败:', error)
        const newMenu: SysMenu = {
          ...menu as SysMenu,
          menu_id: Date.now(),
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
          is_deleted: false
        }
        menuList.value.push(newMenu)
        buildMenuTree()
        console.log('已添加模拟菜单')
      }
    }
  }

  // 编辑菜单
  const updateMenu = async (id: number, menu: SysMenuUpdate, signal?: AbortSignal) => {
    try {
      const response = await request.put(`/api/sys/menus/${id}`, menu, { signal })

      if (response && response.data) {
        const index = menuList.value.findIndex((m: SysMenu) => m.menu_id === id)
        if (index !== -1) {
          menuList.value[index] = { ...menuList.value[index], ...response.data }
          buildMenuTree()
        }
      }
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('编辑菜单失败:', error)
        const index = menuList.value.findIndex((m: SysMenu) => m.menu_id === id)
        if (index !== -1) {
          menuList.value[index] = {
            ...menuList.value[index],
            ...menu,
            updated_at: new Date().toISOString()
          }
          buildMenuTree()
        }
        console.log('已更新模拟菜单')
      }
    }
  }

  // 删除菜单
  const deleteMenu = async (id: number, signal?: AbortSignal) => {
    try {
      await request.delete(`/api/sys/menus/${id}`, { signal })
      menuList.value = menuList.value.filter((m: SysMenu) => m.menu_id !== id)
      buildMenuTree()
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('删除菜单失败:', error)
        menuList.value = menuList.value.filter((m: SysMenu) => m.menu_id !== id)
        buildMenuTree()
        console.log('已删除模拟菜单')
      }
    }
  }

  // 设置当前编辑菜单
  const setCurrentMenu = (menu: SysMenu | null) => {
    currentMenu.value = menu
    isEditing.value = !!menu
  }

  // 初始化时构建菜单树
  buildMenuTree()

  return {
    menuList,
    menuTree,
    currentMenu,
    isEditing,
    fetchMenuList,
    addMenu,
    updateMenu,
    deleteMenu,
    setCurrentMenu,
    buildMenuTree
  }
})